<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>创建线程的第三种方式 | 奔跑的蜗牛 | 虚心若愚</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="Callable,Future">
    <meta name="description" content="使用Callable和Future创建线程从Java5开始，Java提供了Callable接口，该接口提供了一个call()方法作为线程执行体。提供了如下功能。  call()方法可以有返回值。 call()方法可以声明抛出异常。  如何获取call()方法的返回值?Callable接口是Java 5新增的接口，而且不是Runnable接口的子接口，所以不能直接作为Thread的target。ca">
<meta name="keywords" content="Callable,Future">
<meta property="og:type" content="article">
<meta property="og:title" content="创建线程的第三种方式">
<meta property="og:url" content="http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/index.html">
<meta property="og:site_name" content="奔跑的蜗牛">
<meta property="og:description" content="使用Callable和Future创建线程从Java5开始，Java提供了Callable接口，该接口提供了一个call()方法作为线程执行体。提供了如下功能。  call()方法可以有返回值。 call()方法可以声明抛出异常。  如何获取call()方法的返回值?Callable接口是Java 5新增的接口，而且不是Runnable接口的子接口，所以不能直接作为Thread的target。ca">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-03-18T04:09:49.306Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="创建线程的第三种方式">
<meta name="twitter:description" content="使用Callable和Future创建线程从Java5开始，Java提供了Callable接口，该接口提供了一个call()方法作为线程执行体。提供了如下功能。  call()方法可以有返回值。 call()方法可以声明抛出异常。  如何获取call()方法的返回值?Callable接口是Java 5新增的接口，而且不是Runnable接口的子接口，所以不能直接作为Thread的target。ca">
    
        <link rel="alternative" href="/atom.xml" title="奔跑的蜗牛" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/blog/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@1.5.2/css/style.css">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/timg.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/user2.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">windy</h5>
          <a href="mailto:windynature@163.com" title="windynature@163.com" class="mail">windynature@163.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/WindyNature" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/windynature" target="_blank" >
                <i class="icon icon-lg icon-mayun"></i>
                码云
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">创建线程的第三种方式</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">创建线程的第三种方式</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-04-12T04:15:29.000Z" itemprop="datePublished" class="page-time">
  2017-04-12
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/多线程/">多线程</a></li></ul>

            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#使用Callable和Future创建线程"><span class="post-toc-text">使用Callable和Future创建线程</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#如何获取call-方法的返回值"><span class="post-toc-text">如何获取call()方法的返回值?</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Future接口主要公共方法"><span class="post-toc-text">Future接口主要公共方法</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Callable和Future实现例子"><span class="post-toc-text">Callable和Future实现例子</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#实现步骤"><span class="post-toc-text">实现步骤</span></a></li></ol></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">创建线程的第三种方式</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年04月12日 12:15" datetime="2017-04-12T04:15:29.000Z"  itemprop="datePublished">2017-04-12</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/多线程/">多线程</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="使用Callable和Future创建线程"><a href="#使用Callable和Future创建线程" class="headerlink" title="使用Callable和Future创建线程"></a>使用Callable和Future创建线程</h1><p>从Java5开始，Java提供了Callable接口，该接口提供了一个<code>call()</code>方法作为线程执行体。提供了如下功能。</p>
<ul>
<li><font color="red">call()方法可以有返回值。</font></li>
<li>call()方法可以声明抛出异常。</li>
</ul>
<h2 id="如何获取call-方法的返回值"><a href="#如何获取call-方法的返回值" class="headerlink" title="如何获取call()方法的返回值?"></a>如何获取call()方法的返回值?</h2><p>Callable接口是Java 5新增的接口，而且不是Runnable接口的子接口，所以不能直接作为Thread的target。<br>call()方法并不是直接调用，而是作为线程执行体被调用的。</p>
<p>Java5提供Future接口来代表call()方法的返回值，并提供了一个FutureTask实现类，该实现类实现了Future接口和Runnable接口，所以可以作为Thread类的target。</p>
<h3 id="Future接口主要公共方法"><a href="#Future接口主要公共方法" class="headerlink" title="Future接口主要公共方法"></a>Future接口主要公共方法</h3><ul>
<li><code>boolean cancel(boolean mayInterruptIfRunning):</code>试图取消该Future里关联的Callable任务。</li>
<li><code>V get():</code>返回Callable任务里call方法</li>
<li><code>V get(long timeout, TimeUnit unit):</code>返回Callable任务里call()方法的返回值。指定阻塞时间，指定时间无返回值抛<code>TimeoutException</code></li>
<li><code>boolean isCancelled():</code>如果在Callable任务完成前被取消，则返回true.</li>
<li><code>boolean isDone():</code>如果任务已完成，则返回true。</li>
</ul>
<h3 id="Callable和Future实现例子"><a href="#Callable和Future实现例子" class="headerlink" title="Callable和Future实现例子"></a>Callable和Future实现例子</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**实现Callable接口来实现线程类**/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThirdThread</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Integer</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">//实现call方法，作为线程体</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(;i&lt;<span class="number">100</span>;i++) &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + <span class="string">"的循环变量i的值："</span> + i);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ThirdThread rt = <span class="keyword">new</span> ThirdThread();</span><br><span class="line">        <span class="comment">//使用FutureTask来包装Callable对象</span></span><br><span class="line">        FutureTask&lt;Integer&gt; task = <span class="keyword">new</span> FutureTask&lt;Integer&gt;(rt);</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;<span class="number">100</span>;i++) &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName + <span class="string">" 的循环变量i的值:"</span> + i);</span><br><span class="line">            <span class="keyword">if</span>(i==<span class="number">20</span>) &#123;</span><br><span class="line">                <span class="comment">//是指还是以Callable对象来创建并启动线程</span></span><br><span class="line">                <span class="keyword">new</span> Thread(task,<span class="string">"有返回值的线程"</span>).start();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            <span class="comment">//获取线程返回值</span></span><br><span class="line">            System.out.println(<span class="string">"子线程的返回值："</span> + task.get());</span><br><span class="line">        &#125; <span class="keyword">catch</span>(Execption e) &#123;</span><br><span class="line">            e.printStackTracke();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong><font color="red">Callable接口有泛型限制，Callable接口里的泛型形参类型与call()方法返回值类型相同。</font></strong></p>
</blockquote>
<h3 id="实现步骤"><a href="#实现步骤" class="headerlink" title="实现步骤"></a>实现步骤</h3><p>创建并启动返回值的线程的步骤如下：</p>
<ol>
<li>创建Callable的接口实现类，并实现call方法，该方法作为线程执行体，且该call方法具有<code>返回值</code>。</li>
<li>创建Callable实现类的实例，使用FutureTask类来包装Callable对象，该FutureTask对象封装了该Callable对象的call方法的返回值。</li>
<li>使用FutureTask对象作为Thread对象的target创建并启动新线程。</li>
<li>调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。</li>
</ol>
<p><a href="http://ifeve.com/monitors-java-synchronization-mechanism/" target="_blank" rel="noopener">监视器</a></p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-03-18T04:09:49.306Z" itemprop="dateUpdated">2020年3月18日 12:09</time>
</span><br>


        这里写留言或版权声明：<a href="/blog/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/" target="_blank" rel="external">http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/</a>
    </div>
    <footer>
        <a href="http://windynature.oschina.io">
            <img src="/blog/img/user2.jpg" alt="windy">
            windy
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/Callable/">Callable</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/Future/">Future</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/&title=《创建线程的第三种方式》 — 奔跑的蜗牛&pic=http://windynature.oschina.io/img/user2.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/&title=《创建线程的第三种方式》 — 奔跑的蜗牛&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《创建线程的第三种方式》 — 奔跑的蜗牛&url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/&via=http://windynature.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/2017/04/12/java/多线程/线程的生命周期及优先级/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">线程的生命周期及优先级</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/2017/04/05/java/多线程/CountDownLatch详解/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">什么时候使用CountDownLatch</h4>
      </a>
    </div>
  
</nav>



    

<div class="comments" id="comments">
    <div class="ds-thread" data-thread-key="java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）" data-title="创建线程的第三种方式" data-url="http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/"></div>
</div>
<script>
lazyScripts.push('//cdn.bootcss.com/marked/0.3.6/marked.min.js');

var duoshuoQuery = {short_name:'ysblog', theme: 'none'};
lazyScripts.push('//unpkg.com/hexo-theme-material-indigo@1.5.2/js/embed.min.js');


</script>










</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a></span>
            <span>奔跑的蜗牛 &copy; 2015 - 2020</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/&title=《创建线程的第三种方式》 — 奔跑的蜗牛&pic=http://windynature.oschina.io/img/user2.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/&title=《创建线程的第三种方式》 — 奔跑的蜗牛&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《创建线程的第三种方式》 — 奔跑的蜗牛&url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/&via=http://windynature.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://windynature.oschina.io/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };



</script>

<script src="//unpkg.com/hexo-theme-material-indigo@1.5.2/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@1.5.2/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
